package com.changgou.service.impl;

import com.changgou.service.fileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class filServiceImpl implements fileService {


    @Override
    public byte[] readFile(String url) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(url);
            byte[] yy = new byte[1024 * 1024];
            int len = 0;
            while ((len = fileInputStream.read(yy)) != -1) {
                bytes.write(yy);
            }
            fileInputStream.close();
            return bytes.toByteArray();
        } catch (IOException e) {
            System.out.println("找不到文件" + url);
            return new byte[0];
        }
    }



    @Override
    public boolean delFile(Map<String, Object> map)  {
        List<String> lis = (List<String>) map.get("fileurl");
        boolean od = false;
        for (int i = 0; i<lis.size(); i++) {
            od = new File(lis.get(i)).delete();
        }
        return  od;
    }


    @Override
    public String uploadFilerePath(MultipartFile file, Map<String, Object> map) throws IOException {
        String uidname = UUID.randomUUID().toString();
        String filedate = new SimpleDateFormat("yyyy-MM").format(new Date()).toString();

        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 获取文件的后缀名
            String filekzm = fileName.substring(fileName.lastIndexOf("."),fileName.length());
            // 设置文件存储路径
            String filePath = "E:/loadFile";
            //   String path =  fileName;
            String path = "/"+ filedate+"/"+ uidname + filekzm;
            System.out.println(path);
            File dest = new File(filePath+path);
            // 检测是否存在目录

            if (!dest.getParentFile().exists() && !dest.isDirectory()) {
                dest.getParentFile().mkdirs();// 新建文件夹
                dest.createNewFile();
            }else{
                dest.createNewFile();
            }
            //    FileOutputStream     fileOutputStream = new FileOutputStream(filePath+ path);
            file.transferTo(dest);// 文件写入
            return path;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
